<%@ page contentType="text/html; charset=UTF-8"%>
<%@page import="edu.ccut.saturn.component.SaturnData"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<%@ include file="/extjs/include/all.jsp"%>
<title></title>
<script type="text/javascript">
Ext.onReady(function(){
Ext.QuickTips.init();
	var states = [['2','代办'],['3','协办']];
        var simpleStore = new Ext.data.SimpleStore({
            fields: ['state','stateName']
        });
        simpleStore.loadData(states);
	var simple = new Ext.FormPanel({
			renderTo:'form-ct',
			autoHeight:true,
	        frame:true,
	        title: '查询条件',
	        labelWidth: 60,
	        bodyStyle:'width:100%',
	       items: [{
	            layout:'column',
	            items:[{
	                columnWidth:.25,
	                layout: 'form',
	                items: [{
		                    xtype:'textfield',
		                    fieldLabel: '委托人',
		                    name: 'delegate_from_name',
		                    id: 'delegate_from_name',
		                    readOnly:true
		                },{
		                    xtype:'hidden',
		                    name: 'delegate_from',
		                    id: 'delegate_from'
		                }]
	            },{
	                columnWidth:.25,
	                layout: 'form',
	                items: [{
		                    xtype:'button',
		                    text: '选择委托人',
		                    handler:chooseDelegate
		                }]
	            }] 
        }],
        tbar:new Array(
			   new Ext.Toolbar.Button({
						   text:'查询',
						   xtype:"button" ,
						   tooltip:"按条件查询" ,
						   handler:function(){
							   var delegate_from = Ext.get("delegate_from").dom.value;
							   if(delegate_from==''||delegate_from==null){
							   		Ext.MessageBox.alert('警告','请选择委托人');
							   }else{
							   		store.load({params: {start:0,limit:20,userId:Ext.get("delegate_from").dom.value}});
							   }					   		
						   },
						   scope :this}),
			   new Ext.Toolbar.Button({
						   text:'重置',
						   xtype:"button" ,
						   tooltip:"恢复默认值",
						   handler:function(){
						   		simple.getForm().reset();
						   },
						   scope :this}) 
			 ) 
	    });
    var sm = new Ext.grid.CheckboxSelectionModel();
	var cm = new Ext.grid.ColumnModel([
	    new Ext.grid.RowNumberer(),
	    sm, 
	   {header: "工作项名称", dataIndex: 'workitem_name', sortable: false},
       {header: "业务流程名称", dataIndex: 'process_name', sortable: true},
       {header: "流程实例名称", dataIndex: 'process_instance_name', sortable: true},
       {header: "当前状态", dataIndex: 'workitem_state', sortable: true,renderer:showState},
       {header: "启动时间", dataIndex: 'workitem_start_time', sortable: true},
       {header: "时间限制", dataIndex: 'act_inst_limit_number', sortable: true}
	 ]); 
	cm.defaultSortable = true; 
	var store = new Ext.data.JsonStore({
		    url: '${pageContext.request.contextPath}/edu.ccut.saturn.workflow.manager::/delegateModule/action/QueryRunTaskByUserId.action',
		    root: 'result',
		    totalProperty:'count',
		    fields: [
		  		   {name: 'workitem_id', mapping: 'workitem_id'},
		   		   {name: 'workitem_name', mapping: 'workitem_name'},
	               {name: 'process_name', mapping: 'process_name'},
	               {name: 'process_instance_name', mapping: 'process_instance_name'},
		    	   {name: 'workitem_state', mapping: 'workitem_state'},
		    	   {name: 'workitem_start_time', mapping: 'workitem_start_time'},
	               {name: 'act_inst_limit_number', mapping: 'start_time'}
	               ]
		});
		
		var grid = new Ext.grid.GridPanel({
			    bodyStyle:'width:100%',
	       	    store: store,
			    sm:sm,
			    cm:cm,
		        renderTo:document.body,
		        height:500,
		        frame:true,
		        loadMask: {msg:'正在加载数据，请稍侯……'},
        		bbar: new Ext.PagingToolbar({ 
		            pageSize: 20, 
		            store: store, 
		            displayInfo: true, 
		            displayMsg: '当前显示 {0} - {1}条记录 /共 {2}条记录',
		            emptyMsg: "没有数据显示" 
	    		}),
	    		tbar:new Array(
					new Ext.Toolbar.Button({
						   text:'设置代办',
						   xtype:"button" ,
						   tooltip:"设置选择的工作项为代办" ,
						   handler:setDelegate,
						   scope :this})) 
		});

	   function chooseDelegate(){
			var root=new Ext.tree.AsyncTreeNode({
				id:"root_participant",
				text:"参与者"});
			var tree=new Ext.tree.TreePanel({
				root:root,
				loader: new Ext.tree.TreeLoader({url:'${pageContext.request.contextPath}/edu.ccut.saturn.workflow.manager::/agentManagerModule/action/GetTreeJson.action'}),
				width:400,
				autoScroll: true
			});	

		  tree.on('click', function(node){
					addDelegateFrom(node.id,node.text);
				},this);
	       var window = new Ext.Window({
				title: '添加委托人',
				width: 500,
				height:300,
				minWidth: 300,
				minHeight: 200,
				layout: 'fit',
				plain:true,
				items:tree,
				buttonAlign:'center',
				modal:true
			});
			window.show();
		}
		
	function addDelegateFrom(userid,name){
		 if(userid=='root_participant'){
			return false;
		 }
		 if(userid!='rootDept'&& userid!='rootRole'){
		 	var type = userid.split('_')[0];
		 	var id = userid.split('_')[1];
		 	if(type=='deptUser'||type=='roleUser'){
		 		Ext.get("delegate_from").dom.value =id;
		 		Ext.get("delegate_from_name").dom.value =name;
		 	}
		 }
	 }
	
		function setDelegate(){
			var arrRecord = sm.getSelections();
			var workitemIds = '';
			if(arrRecord.length==0){
		 		Ext.MessageBox.alert('警告','至少选择一条记录');
		 	}else{
		 		for (var i = 0, len = arrRecord.length; i < len; i++){    	   	   	  	 
			   	   	  	 workitemIds += arrRecord[i].data["workitem_id"];  
			   	   	  	 workitemIds += ',' ;	
				} 
			    if(workitemIds.length > 0){
	 					workitemIds = workitemIds.substring(0,workitemIds.length - 1) ;
				}
				 var panel = new Ext.FormPanel({
					 	frame:true,
					 	layout:'form',
					    items: [{
				            layout:'column',
				            items: [{
				            	columnWidth:.5,
				                layout: 'form',
				                items: [{
					                    xtype:'textfield',
					                    fieldLabel: '代办人',
					                    name: 'delegate_name',
					                    id: 'delegate_name',
					                    readOnly:true
					                },{
					                    xtype:'hidden',
					                    name: 'delegate_to',
					                    id: 'delegate_to'
					                },{
					                    xtype:'textarea',
					                    fieldLabel: '代办原因',
					                    width:130,
					                    name: 'delegate_reason',
					                    id: 'delegate_reason',
					                    allowBlank:false,
		                				msgTarget:'qtip'
					                },{
					                    xtype:'hidden',
					                    name: 'delegate_to_user_type',
					                    id: 'delegate_to_user_type'
					                },{
					                columnWidth:.5,
					                layout: 'form',
					                items: [{
						                    xtype:'combo',
						                    fieldLabel: '代办方式',
						                    name:'delegate_type',
						                    hiddenName:'operate_type',
						                    store: simpleStore,
						                    displayField: 'stateName',
						                    valueField: 'state',
						                    value:'2',
						                    mode: 'local',
										    triggerAction: 'all',
										    width:130,
										    editable: false,
				 							typeAhead: true
						                }]
	            				}]
					            },{
				                columnWidth:.25,
				                layout: 'form',
				                items: [{
					                    xtype:'button',
					                    text: '选择代办人',
					                    handler:chDelegateTo
					                }]
				           	 }]
			       		 }],
			             buttons: [{
				            text: '确认',
				            handler:function(){
				            	if(Ext.get("delegate_name").dom.value==''){
				            		Ext.Msg.alert('信息',"请选择代办人",function(){
												      return false;
										     }); 
				            	}else if(panel.form.isValid()){
					            	Ext.Ajax.request({
									     method : 'POST',                           
									     url: '${pageContext.request.contextPath}/edu.ccut.saturn.workflow.manager::/delegateModule/action/SetDelegate.action',     
									     success:function(request){  
									      	var myResult = Ext.util.JSON.decode(request.responseText); 
									      	Ext.Msg.alert('信息',myResult.message,function(){
												      store.load();
										     });          
												window.close(); 
										       //document.location.reload();
									     },
									     failure:function(){                          
									      	   Ext.Msg.alert("错误", "与后台联系的时候出现了问题");
									     },
									     params:{
									     		delegate_to:Ext.get("delegate_to").dom.value, 
									     		delegate_from:Ext.get("delegate_from").dom.value, 
									     		delegate_to_user_type:Ext.get("delegate_to_user_type").dom.value,
									     		workitemIds:workitemIds,
									     		delegate_reason:Ext.get("delegate_reason").dom.value,
									     		operate_type:Ext.get("operate_type").dom.value
									     } 
					     			});
					              }
				            	}
			       		 },{
				            text: '重置',
				            handler:function(){
				            	panel.getForm().reset();
				            }
				        }]
			         });
			        
			         var window = new Ext.Window({
			            title: '设置代办',
						width: 500,
						height:200,
						layout: 'fit',
						plain:true,
						items:panel,
						buttonAlign:'center',
						modal:true
			           });
			           
					window.show();			
		 	}
		}
		
		  function chDelegateTo(){
			var root=new Ext.tree.AsyncTreeNode({
				id:"root_participant",
				text:"参与者"});
			var tree=new Ext.tree.TreePanel({
				root:root,
				loader: new Ext.tree.TreeLoader({url:'${pageContext.request.contextPath}/edu.ccut.saturn.workflow.manager::/agentManagerModule/action/GetTreeJson.action'}),
				width:400,
				autoScroll: true
			});	

		  tree.on('click', function(node){
					addDelegateTo(node.id,node.text);
				},this);
	       var window = new Ext.Window({
				title: '添加代办人',
				width: 500,
				height:300,
				minWidth: 300,
				minHeight: 200,
				layout: 'fit',
				plain:true,
				items:tree,
				buttonAlign:'center',
				modal:true
			});
			window.show();
		}
		
	function addDelegateTo(userid,name){
		 var delegate_from = Ext.get("delegate_from").dom.value;
		 if(userid=='root_participant'){
			return false;
		 }
		 if(userid!='rootDept'&& userid!='rootRole'){
		 	var type = userid.split('_')[0];
		 	var id = userid.split('_')[1];
		 	if((type=='deptUser'||type=='roleUser')&&delegate_from!=id&&type!='user'){
		 		Ext.get("delegate_to").dom.value =id;
		 		Ext.get("delegate_to_user_type").dom.value ='user';
		 		Ext.get("delegate_name").dom.value =name;
		 	}else if(type=='dept'){
		 		Ext.get("delegate_to_user_type").dom.value ="dept";	
		 		Ext.get("delegate_to").dom.value =id;
		 		Ext.get("delegate_name").dom.value =name; 		
		 	}
		 	else if(type=='role'){
		 		Ext.get("delegate_to_user_type").dom.value ="role";
		 		Ext.get("delegate_to").dom.value =id;
		 		Ext.get("delegate_name").dom.value =name;
		 	}
		 }
	 }
	 
	 function showState(value){
	 	if(value=='10'){
	 		return '运行';
	 	}
	 	if(value=='10'){
	 		return '完成';
	 	}
	 }
});
</script>
<div id='form-ct' width='100%'></div>
<div id='task-grid' width='100%'></div>
</head>
</html>